const { group, select, text, log, spinner, isCancel, cancel } = require("@clack/prompts");
const { getSettings } = require("./settings");
const path = require("path");
const fs = require("fs-extra");
const { Workbook } = require("exceljs");
const { getI18nTranslates, mergeTranslates } = require("../utils");

async function getTranslateData(file) {
  try {
    const workbook = new Workbook();
    await workbook.xlsx.readFile(file);
    const sheet = workbook.getWorksheet(1);
    const tabel = [];
    const translates = {};

    sheet.eachRow((row) => {
      const data = [];
      tabel.push(data);
      row.eachCell({ includeEmpty: true }, (cell) => data.push(cell.value));
    });
    const languages = tabel.shift().slice(1);
    for (const item of tabel) {
      const [key, ...data] = item;
      translates[key] = Object.fromEntries(languages.map((lang, i) => [lang, data[i] ?? ""]));
    }
    return { languages, translates };
  } catch (error) {
    log.error(`Error:${error.message}`);
    process.exit(0);
  }
}

async function main() {
  const settings = await getSettings();

  const config = await group({
    type: () =>
      select({
        message: "导入模式",
        initialValue: "update",
        options: [
          {
            value: "reset",
            label: "重置",
            hint: "重新生成i18n配置文件（将清除所有现有配置，基于当前翻译文件全新构建）",
          },
          { value: "update", label: "增量更新", hint: "添加新增翻译内容（保留现有翻译数据，仅补充未收录的翻译项）" },
          {
            value: "overwrite",
            label: "强制更新",
            hint: "覆盖更新翻译内容（用当前翻译文件强制替换所有匹配键名的翻译数据）",
          },
        ],
      }),
    filename: () =>
      text({
        message: "翻译文件",
        placeholder: "请输入文件完整路径，或者拖拽文件到这里，如果是相对路径，则根目录为当前项目目录。",
        validate: (value) => !value && "请输入文件路径",
      }),
  });

  if (isCancel(config)) {
    cancel("操作取消");
    process.exit(0);
  }

  config.filename = config.filename.replace(/^[&"'\s]+|[&"'\s]+$/g, "");

  const i18n = await getI18nTranslates(settings.languageDir);
  const translated = await getTranslateData(config.filename);
  //prettier-ignore
  const merged = config.type === 'reset' ? translated.translates : mergeTranslates(i18n.translates, translated.translates, config.type === 'overwrite');
  const languages = Array.from(new Set([...i18n.languages, ...translated.languages]));
  const translates = {};
  const spin = spinner();

  spin.start("正在导入翻译");
  for (const language of languages) {
    translates[language] = {};

    for (const [key, values] of Object.entries(merged)) {
      const pathes = key.split(".");
      const finalKey = pathes.pop();
      let current = translates[language];

      for (const key of pathes) {
        if (!current[key]) current[key] = {};
        current = current[key];
      }

      current[finalKey] = values[language];
    }
  }

  for (const language of languages) {
    const filePath = path.join(settings.languageDir, `${language}.json`);
    await fs.writeFile(filePath, JSON.stringify(translates[language], null, 2));
  }
  spin.stop("翻译已导入完毕。");
}

module.exports = { main };

/*

{
  test.abc.def: {zh: '张三',en:'zhangsan'},
  test.abc.ghi: {zh: '李四',en:'lisi'},
  test.mln:     {zh: '王五'},
}

{
  test.abc.def: {zh: '张三',en:'zhangsan'},
  test.abc.ghi: {zh: '李四',en:'lisi'},
  test.mln:     {en:'wangwu'},
  test.jkl:     {zh: '赵六',en:'zhaoliu'},
}

xlsx
[
  ['key', 'zh', 'en'],
  ['test.abc.def', '张三-new', 'zhangsan'],
  ['test.abc.ghi', '李四', 'lisi-2'],
  ['test.mln', '王五', 'wangwu'],
  ['test.jkl', '赵六', 'zhaoliu'],
]

原始i18n配置文件
zh.json
{
  test: {
    abc: {
      def: '张三',
      ghi: '李四'
    },
    'mln': '王五'
  }
}

更新后的i18n配置文件
zh.json
{
  test: {
    abc: {
      def: '张三-new',
      ghi: '李四'
    },
    'mln': '王五',
    'jkl': '赵六'
  }
}
en.json
{
  test: {
    abc: {
      def: 'zhangsan',
      ghi: 'lisi-2'
    },
    'mln': 'wangwu',
    'jkl': 'zhaoliu'
  }
}

*/
